import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { checkSuperAdmin } from '@/utils/auth'
import { jwtDecode } from 'jwt-decode';

export const useUserStore = defineStore('user',()=>{
    //判断用户是否登录
    const isLoggedIn =  ref(localStorage.getItem('isLoggedIn') === 'true');
    const router = useRouter()
    const route = useRoute()
    //登录后重导向路径
    const redirectPath = ref(route.path)
    const isSuperAdmin = ref(false)
    async function login(form:any,token:any){
        localStorage.setItem('token', token);
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('username',form.username);
        localStorage.setItem('password',form.password);
        isSuperAdmin.value = await checkSuperAdmin()
        isLoggedIn.value = true
        router.push({path:redirectPath.value})
    }            
    function logout(){
        localStorage.removeItem('token');
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        isSuperAdmin.value = false
        isLoggedIn.value = false
        router.push('/login')
    }   
    const checkTokenExpiration = () => {
        const token = localStorage.getItem('token');
        if (!token) return false;
      
        try {
          const decoded: any = jwtDecode(token); // 解码 JWT
          const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间戳
          return decoded.exp > currentTime; // 如果 token 没过期则返回 true
        } catch (e) {
          return false;
        }
    };
    return {isLoggedIn,isSuperAdmin, redirectPath,login,logout,checkTokenExpiration}
})
 